var Log = require('../models/log');


function totalHours(req, res, next){
    Log.aggregate({
            $match: {
                
            }
        },
        {
            $group: {
                _id:null,
                duration: {$sum: '$duration'}
            }
        },
        {

            $project: {
                duration: 1
            }

        }).then((result)=>{
            if(result && result.length > 0){
                res.json({totalHours:result[0].duration});
            } else {
                res.json({totalHours:0});
            }
            
        })
        .catch((error)=>{
            console.error(error);
            res.status(500);
            res.end();
        })
}

//统计指定用户的
function perUser(username){
    return Log.aggregate({
        $match: {
            user: username,
        }
    },
    {
        $group: {
            _id:null,
            duration: {$sum: '$duration'}
        }
    },
    {

        $project: {
            duration: 1
        }

    }).then((result)=>{
        if(result && result.length > 0){
            return Promise.resolve(result[0].duration);
        } else {
            return Promise.resolve(0);
        }
        
    })
}


function currentUser(req, res, next){
    let userName = req.session.user.loginname;
    Promise.all([
        perUser(userName),
        Log.count({
            user: userName,
        }),
    ]).then(([totalHours, logAmount])=>{
        res.json({
            totalHours,
            logAmount
        })
    }).catch((error)=>{
        console.error(error);
        res.status(500);
        res.end();
    })
}
module.exports = {
    totalHours,
    currentUser,
}